import tensorflow as tf
from tensorflow import keras
from sklearn.datasets import fetch_california_housing
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from self_mudle.plot_learning_curves import plot_learning_curves

dataset = fetch_california_housing()
train_x, test_x, train_y, test_y = train_test_split(dataset.data,dataset.target,test_size=0.2,random_state=42)
train_x, valid_x, train_y, valid_y = train_test_split(train_x,train_y,test_size=0.2,random_state=42)


scaler = StandardScaler()
train_x = scaler.fit_transform(train_x)
valid_x = scaler.transform(valid_x)
test_x = scaler.transform(test_x)

# 子类API搭配build函数使用
class wide_deep_model(keras.models.Model):
    def __init__ (self):  # 初始化函数
        super(wide_deep_model,self).__init__()  # 调用父类初始化函数
        """定义网络层次"""
        self.hidden_layer1 = keras.layers.Dense(30, activation='relu')
        self.hidden_layer2 = keras.layers.Dense(30, activation='relu')
        self.output_layer = keras.layers.Dense(1)

    def call(self, input):
        """完成正向计算"""
        hidden1 = self.hidden_layer1(input)
        hidden2 = self.hidden_layer2(hidden1)
        concat = keras.layers.concatenate([input,hidden2])
        output = self.output_layer(concat)

        return output

# 创建模型对象或者在Sequential中调用
model = wide_deep_model()

# model = keras.Sequential([
#     wide_deep_model()
# ])

model.build(input_shape=(None,8))
model.summary()

model.compile( 
    optimizer = keras.optimizers.Adam(0.001),
    loss = keras.losses.mean_squared_error
)

history = model.fit(train_x, train_y, epochs=10, validation_data = (valid_x, valid_y))
model.evaluate(test_x,test_y)
# plot_learning_curves(history)
